package com.catering.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class AMapService {
    
    private static final Logger log = LoggerFactory.getLogger(AMapService.class);
    
    @Value("${amap.key}")
    private String apiKey;
    
    private final String GEOCODE_URL = "https://restapi.amap.com/v3/geocode/regeo";
    private final String IP_LOCATION_URL = "https://restapi.amap.com/v3/ip";
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    /**
     * 根据经纬度获取地址信息
     * @param longitude 经度
     * @param latitude 纬度
     * @return 地址信息
     */
    public JSONObject getAddressByLocation(double longitude, double latitude) {
        try {
            String url = String.format("%s?key=%s&location=%s,%s", 
                GEOCODE_URL, apiKey, longitude, latitude);
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            JSONObject result = JSONObject.parseObject(response.getBody());
            
            if ("1".equals(result.getString("status"))) {
                return result.getJSONObject("regeocode");
            } else {
                log.error("获取地址信息失败: {}", result.getString("info"));
                return null;
            }
        } catch (Exception e) {
            log.error("获取地址信息异常", e);
            return null;
        }
    }
    
    /**
     * 根据IP获取位置信息
     * @param ip IP地址
     * @return 位置信息
     */
    public JSONObject getLocationByIP(String ip) {
        try {
            String url = String.format("%s?key=%s&ip=%s", 
                IP_LOCATION_URL, apiKey, ip);
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            JSONObject result = JSONObject.parseObject(response.getBody());
            
            if ("1".equals(result.getString("status"))) {
                return result;
            } else {
                log.error("获取IP位置信息失败: {}", result.getString("info"));
                return null;
            }
        } catch (Exception e) {
            log.error("获取IP位置信息异常", e);
            return null;
        }
    }
} 